package com.braveman.im.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.braveman.im.R;
import com.braveman.im.api.Api;
import com.braveman.im.bean.AddFriendsAndGroupBean;
import com.braveman.im.bean.DataListBean;
import com.braveman.im.bean.GetDetailsByImGroupId;
import com.braveman.im.bean.JoinBean;
import com.braveman.im.bean.LocationBean;
import com.braveman.im.bean.NoticeBean;
import com.braveman.im.bean.SendLoveNotifyDetailsBean;
import com.braveman.im.constant.Constants;
import com.braveman.im.factory.FragmentFactory;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.ui.activity.CardActivity;
import com.braveman.im.ui.activity.DetailsNoticeActivity;
import com.braveman.im.ui.activity.DetailsPalteformNotifyActivity;
import com.braveman.im.ui.activity.SystemNotifyActivity;
import com.braveman.im.ui.activity.WebViewActivity;
import com.braveman.im.ui.activity.message.ChatAllActivity;
import com.braveman.im.ui.adapter.CompanyCheckAdapter;
import com.braveman.im.ui.adapter.FragAdapter;
import com.braveman.im.ui.adapter.FriendsCheckAdapter;
import com.braveman.im.ui.adapter.GroupCheckAdapter;
import com.braveman.im.ui.adapter.NoticeAdapter;
import com.braveman.im.ui.adapter.SendLoveAdapter;
import com.braveman.im.ui.dialog.TipsDialog;
import com.braveman.im.ui.weiget.RefreshRecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseFragment;
import com.ht.baselibs.ui.base.BaseWebViewActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.iflytek.cloud.thirdparty.V;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import ezy.ui.layout.LoadingLayout;
import retrofit2.Call;
import retrofit2.Response;

public class MessageFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener {
    private TextView mTvMessageForMine;
    private TextView mTvMessageForGroup;
    private TextView mTvMessageForCompany;
    private TextView mTvMessageForFriends;
    private TextView mTvNoticeForGroupOwner;
    private TextView mTvMessageForSystem;
    private TextView mTvNoticeForService;
    private TextView mTvNoticeForSystem;
    private TextView mTvLovingHeart;
    private TextView mTvAdvertising;
    private TextView mTvShopping;
    private List<LocationBean> mMessageList = new ArrayList<>();
    private EaseConversationList conversationListView;
    protected List<EMConversation> conversationList = new ArrayList<>();
    protected List<EMConversation> conversationListAll = new ArrayList<>();
    protected List<EMConversation> conversationListForPerson = new ArrayList<>();
    protected List<EMConversation> conversationListForGroup = new ArrayList<>();
    protected List<EMConversation> conversationListForCompany = new ArrayList<>();

    private SwipeRefreshLayout mSwipeLayout;
    private LoadingLayout mLoadingLayout;
    private RecyclerView mLvActivityListMember;

    private List<DataListBean> dataList = new ArrayList<>();
    private NoticeAdapter noticeAdapter;
    private SendLoveAdapter sendLoveAdapter;
    private LinearLayout mLlFragSystemNotify;


    private RelativeLayout mRlUnderway;
    private RelativeLayout mRlDaishenhe;
    private TextView mTvTitle1;
    private TextView mIvShenHeZhong;
    private RelativeLayout mRlOver;
    private TextView mTvTitle2;
    private TextView mIvYiShenHe;
    private RelativeLayout mRlActivityFlat;
    private TextView mTvTitle3;
    private TextView mIvYiShenHe2;
    private CompanyCheckAdapter checkAdapter;
    private List<DataListBean> systemNotify = new ArrayList<>();
    private int typeNotifyCode = 0;//0-2系统消息  3 群主公告
    private GroupCheckAdapter groupCheckAdapter;
    private FriendsCheckAdapter friendsCheckAdapter;
    private TextView mTvSystemNotifyLine;
    private int pageNo = 1;
    private boolean isLastPage = false;
    private TipsDialog mTipsDialog;
    public static final int REQUEST_PERMISSION_CALL = 0;


    @Override
    protected boolean isStaticPage() {
        return true;
    }


    @Override
    protected View initContentView() {
        return LayoutInflater.from(mContext).inflate(R.layout.frag_home_message, null);
    }

    @Override
    protected void initChildView() {
        mTvMessageForMine = findViewById(R.id.tv_message_for_mine);
        mTvMessageForGroup = findViewById(R.id.tv_message_for_group);
        mTvMessageForCompany = findViewById(R.id.tv_message_for_company);
        mTvMessageForFriends = findViewById(R.id.tv_message_for_friends);
        mTvNoticeForGroupOwner = findViewById(R.id.tv_notice_for_group_owner);
        mTvMessageForSystem = findViewById(R.id.tv_message_for_system);
        mTvNoticeForService = findViewById(R.id.tv_notice_for_service);
        mTvNoticeForSystem = findViewById(R.id.tv_notice_for_system);
        mTvLovingHeart = findViewById(R.id.tv_loving_heart);
        mTvAdvertising = findViewById(R.id.tv_advertising);
        mTvShopping = findViewById(R.id.tv_shopping);


        mSwipeLayout = findViewById(R.id.swipe_layout);
        mLoadingLayout = findViewById(R.id.loading_layout);
        mLvActivityListMember = findViewById(R.id.lv_Activity_list_member);

        mLvActivityListMember.setLayoutManager(new LinearLayoutManager(mContext));
        noticeAdapter = new NoticeAdapter(R.layout.item_notice_details, dataList);
        sendLoveAdapter = new SendLoveAdapter(R.layout.item_notice_details, dataList);
        mLlFragSystemNotify = findViewById(R.id.ll_frag_system_notify);
        checkAdapter = new CompanyCheckAdapter(R.layout.item_company_check, systemNotify);
        groupCheckAdapter = new GroupCheckAdapter(R.layout.item_company_check, systemNotify);
        friendsCheckAdapter = new FriendsCheckAdapter(R.layout.item_company_check, systemNotify);


        mRlUnderway = findViewById(R.id.rl_underway);
        mRlDaishenhe = findViewById(R.id.rl_daishenhe);
        mTvTitle1 = findViewById(R.id.tv_title1);
        mIvShenHeZhong = findViewById(R.id.iv_shen_he_zhong);
        mRlOver = findViewById(R.id.rl_over);
        mTvTitle2 = findViewById(R.id.tv_title2);
        mIvYiShenHe = findViewById(R.id.iv_yi_shen_he);
        mRlActivityFlat = findViewById(R.id.rl_activity_flat);
        mTvTitle3 = findViewById(R.id.tv_title3);
        mIvYiShenHe2 = findViewById(R.id.iv_yi_shen_he2);
        mTvSystemNotifyLine = findViewById(R.id.tv_system_notify_line);
        mTvMessageForMine.setSelected(true);
        reLoad(0);

    }


    @Override
    protected void load() {
        DoNetWorkgetAllMessage();
    }


    private void DoNetWorkgetAllMessage() {
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        ArrayList<String> imGroupIds = new ArrayList<>();

        conversationListForGroup.clear();
        conversationListForPerson.clear();
        conversationListForCompany.clear();
        conversationListAll.clear();
        for (EMConversation em : conversationList) {
            switch (em.getType()) {
                case Chat:
                    conversationListForPerson.add(em);
                    break;
                case GroupChat:
                    conversationListAll.add(em);
                    break;
                case ChatRoom:
                    break;
            }

        }
        imGroupIds.clear();
        for (EMConversation imId : conversationListAll) {
            imGroupIds.add(imId.conversationId());
        }
        if (imGroupIds == null || imGroupIds.size() == 0) {
            return;
        }

        ApiManager.getApi().getByImGroupIds(imGroupIds).enqueue(new NetCallBack<List<GetDetailsByImGroupId>>() {
            @Override
            protected void onSuccess(Call<List<GetDetailsByImGroupId>> call, Response<List<GetDetailsByImGroupId>> response) {
                if (response != null) {
                    conversationListForCompany.clear();
                    conversationListForGroup.clear();
                    List<GetDetailsByImGroupId> list = response.body();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).groupType.equals("company")) {
                            conversationListAll.get(i).setExtField(list.get(i).name);
                            conversationListForCompany.add(conversationListAll.get(i));
                        } else if (list.get(i).groupType.equals("individual")) {
                            conversationListAll.get(i).setExtField(list.get(i).name);
                            conversationListForGroup.add(conversationListAll.get(i));
//                            conversationListView = (EaseConversationList) getView().findViewById(R.id.list_ease_conversation);
//                            conversationListView.init(conversationListForGroup);
                        }
                    }
                    if (conversationListView != null)
                        conversationListView.refresh();
                }
            }
        });


    }


    @Override
    protected void setChildViewListener() {
        findViewById(R.id.tv_message_for_mine).setOnClickListener(this);
        findViewById(R.id.tv_message_for_group).setOnClickListener(this);
        findViewById(R.id.tv_message_for_company).setOnClickListener(this);
        findViewById(R.id.tv_message_for_friends).setOnClickListener(this);
        findViewById(R.id.tv_notice_for_group_owner).setOnClickListener(this);
        findViewById(R.id.tv_message_for_system).setOnClickListener(this);
        findViewById(R.id.tv_notice_for_service).setOnClickListener(this);
        findViewById(R.id.tv_notice_for_system).setOnClickListener(this);
        findViewById(R.id.tv_loving_heart).setOnClickListener(this);
        findViewById(R.id.tv_advertising).setOnClickListener(this);
        findViewById(R.id.tv_shopping).setOnClickListener(this);

        noticeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });

        mLoadingLayout.setRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pageNo = 1;
                doNetWOrk(typeNotifyCode);
            }
        });
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                doNetWOrk(typeNotifyCode);
            }
        });

        mRlUnderway.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                reSelect();
                mRlUnderway.setSelected(true);
                mIvShenHeZhong.setVisibility(View.VISIBLE);
                typeNotifyCode = 0;
                pageNo = 1;
                doNetWOrk(typeNotifyCode);

            }
        });
        mRlOver.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                reSelect();
                mRlOver.setSelected(true);
                mIvYiShenHe.setVisibility(View.VISIBLE);
                typeNotifyCode = 1;
                pageNo = 1;
                doNetWOrk(typeNotifyCode);

            }
        });

        mRlActivityFlat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reSelect();
                mRlActivityFlat.setSelected(true);
                mIvYiShenHe2.setVisibility(View.VISIBLE);
                typeNotifyCode = 2;
                pageNo = 1;
                doNetWOrk(typeNotifyCode);
            }
        });

        friendsCheckAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                String applicationStatus = "";
                String id = systemNotify.get(position).id;
                switch (view.getId()) {
                    case R.id.iv_item_company_check_agree:
                        applicationStatus = "agree";
                        doAuditFriend(applicationStatus, id);
                        break;
                    case R.id.iv_item_company_check_refuse:
                        applicationStatus = "refuse";
                        doAuditFriend(applicationStatus, id);
                        break;
                }
            }
        });
        sendLoveAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                switch (typeNotifyCode) {
                    case 6:
                        // TODO: 17/10/28 跳转爱心详情
                        bundle.putString(BaseWebViewActivity.TITLE, "爱心详情");
                        bundle.putString(BaseWebViewActivity.URL, "http://39.106.43.56/app/html/love.html");
                        ActivityUtils.startActivity(mContext, WebViewActivity.class, bundle);
                        break;
                    case 7:
                        // TODO: 17/10/28 跳转广告详情
                        bundle.putString(BaseWebViewActivity.TITLE, "广告详情");
                        bundle.putString(BaseWebViewActivity.URL, "http://39.106.43.56/app/html/ad.html");
//                        bundle.putString(BaseWebViewActivity.URL, "http://39.106.43.56/app/html/indes.html"+"?token="+SharedPreferencesUtils.getString(Constants.TOKEN,""));
                        ActivityUtils.startActivity(mContext, WebViewActivity.class, bundle);
                        break;
                    default:
                        UIUtils.showToast("系统错误，请重试");
                }
            }
        });

        sendLoveAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                switch (typeNotifyCode) {
                    case 6:
                        switch (view.getId()) {
                            case R.id.tv_phone_icon:
                                if (dataList != null && dataList.size() > 0)
                                    call(dataList.get(position).contactPhone);
                                break;
                        }
                        break;
                    case 7:
                        break;
                    default:
                        UIUtils.showToast("系统错误，请重试");
                }

            }
        });
        friendsCheckAdapter.setOnLoadMoreListener(this, mLvActivityListMember);
        noticeAdapter.setOnLoadMoreListener(this, mLvActivityListMember);
        checkAdapter.setOnLoadMoreListener(this, mLvActivityListMember);
        groupCheckAdapter.setOnLoadMoreListener(this, mLvActivityListMember);
        friendsCheckAdapter.setOnLoadMoreListener(this, mLvActivityListMember);
        sendLoveAdapter.setOnLoadMoreListener(this, mLvActivityListMember);

        doItemOnclick();
    }

    private void call(final String phone) {
        mTipsDialog = new TipsDialog(mContext);
        mTipsDialog.setTitileHint("是否拨打电话\n");
        mTipsDialog.show();
        mTipsDialog.setOnDialogTipsClickListener(new TipsDialog.OnDialogTipsClickListener() {

            @Override
            public void doEnter() {
                mTipsDialog.dismiss();
            }

            @Override
            public void doCancel() {
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + phone);
                intent.setData(data);
                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PERMISSION_CALL
                    );
                    return;
                }
                startActivity(intent);
                mTipsDialog.dismiss();
            }
        });
    }

    private void doItemOnclick() {


        noticeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                switch (typeNotifyCode) {
                    case 3:
                        // TODO: 17/10/28 跳转群主公告详情
                        if (dataList != null) {
                            String id = dataList.get(position).id;
                            bundle.putString("detailsId", id);
                            ActivityUtils.startActivity(mContext, DetailsNoticeActivity.class, bundle);
                        } else {
                            UIUtils.showToast("数据异常，请刷新页面重试");
                        }

                        break;
                    case 4:
                        // TODO: 17/10/28 跳转平台公告详情
                        if (dataList != null) {
                            String id = dataList.get(position).id;
                            bundle.putString("detailsId", id);
                            ActivityUtils.startActivity(mContext, DetailsPalteformNotifyActivity.class, bundle);
                        }
                        break;
                    case 5:
                        // TODO: 17/10/28 跳转系统公告详情
                        break;
                }
            }
        });
    }

    private void doAuditFriend(String refuseReason, String id) {
        final String to = refuseReason.equals("agree") ? "已同意" : "已拒绝";
        AddFriendsAndGroupBean addFriends = new AddFriendsAndGroupBean();

        switch (typeNotifyCode) {
            case 0:
                addFriends.applicationStatus = refuseReason;
                addFriends.id = id;
                addFriends.refuseReason = "dfsf";
                mLoadingLayout.showLoading();
                ApiManager.getApi().auditFriends(addFriends).enqueue(new NetCallBack<AddFriendsAndGroupBean>() {
                    @Override
                    protected void onSuccess(Call<AddFriendsAndGroupBean> call, Response<AddFriendsAndGroupBean> response) {
                        UIUtils.showToast("操作成功," + to);
                        pageNo = 1;
                        doNetWOrk(typeNotifyCode);
                    }

                    @Override
                    public void onFailure(Call<AddFriendsAndGroupBean> call, Throwable t) {
                        UIUtils.showToast("操作失败");
                        pageNo = 1;
                        mLoadingLayout.showError();
                    }
                });
                break;
            case 1:
                addFriends.applicationStatus = refuseReason;
                addFriends.applicationId = id;
                addFriends.refuseReason = "dfsf";
                mLoadingLayout.showLoading();
                ApiManager.getApi().auditGroup(addFriends).enqueue(new NetCallBack<AddFriendsAndGroupBean>() {
                    @Override
                    protected void onSuccess(Call<AddFriendsAndGroupBean> call, Response<AddFriendsAndGroupBean> response) {
                        UIUtils.showToast("操作成功," + to);
                        pageNo = 1;
                        doNetWOrk(typeNotifyCode);
                    }

                    @Override
                    public void onFailure(Call<AddFriendsAndGroupBean> call, Throwable t) {
                        UIUtils.showToast("操作失败");
                        mLoadingLayout.showError();
                    }
                });
                break;
            case 2:
                mLoadingLayout.showLoading();
                addFriends.applicationStatus = refuseReason;
                addFriends.applicationId = id;
                addFriends.refuseReason = "dfsf";
                ApiManager.getApi().auditPlateform(addFriends).enqueue(new NetCallBack<AddFriendsAndGroupBean>() {
                    @Override
                    protected void onSuccess(Call<AddFriendsAndGroupBean> call, Response<AddFriendsAndGroupBean> response) {
                        UIUtils.showToast("操作成功," + to);
                        pageNo = 1;
                        doNetWOrk(typeNotifyCode);
                    }

                    @Override
                    public void onFailure(Call<AddFriendsAndGroupBean> call, Throwable t) {
                        UIUtils.showToast("操作失败");
                        mLoadingLayout.showError();
                    }
                });
                break;
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        reSelect();
        switch (v.getId()) {
            case R.id.tv_message_for_mine://@我
                mTvMessageForMine.setSelected(true);
                reLoad(0);
                break;
            case R.id.tv_message_for_group://群
                mTvMessageForGroup.setSelected(true);
                reLoad(1);
                break;
            case R.id.tv_message_for_company://单位
                mTvMessageForCompany.setSelected(true);
                reLoad(2);
                break;
            case R.id.tv_message_for_friends://好友
                mTvMessageForFriends.setSelected(true);
                reLoad(3);
                break;
            case R.id.tv_loving_heart://爱心
                mTvLovingHeart.setSelected(true);
                typeNotifyCode = 6;
                reLoad(4);
                break;
            case R.id.tv_advertising://广告
                mTvAdvertising.setSelected(true);
                typeNotifyCode = 7;
                reLoad(5);
                break;
            case R.id.tv_shopping://商城
                mTvShopping.setSelected(true);
                reLoad(6);
                break;
            case R.id.tv_notice_for_group_owner://群主公告
                mTvNoticeForGroupOwner.setSelected(true);
                typeNotifyCode = 3;
                reLoad(8);
                break;
            case R.id.tv_message_for_system://系统消息
                mTvMessageForSystem.setSelected(true);
                typeNotifyCode = 0;
                mRlUnderway.setSelected(true);
                mIvShenHeZhong.setVisibility(View.VISIBLE);
                reLoad(7);
                break;
            case R.id.tv_notice_for_service://平台公告
                mTvNoticeForService.setSelected(true);
                typeNotifyCode = 4;
                reLoad(9);
                break;
            case R.id.tv_notice_for_system://系统公告
                mTvNoticeForSystem.setSelected(true);
                typeNotifyCode = 5;
                reLoad(10);
                break;
        }

    }

    private void reSelect() {
        mTvMessageForMine.setSelected(false);
        mTvMessageForGroup.setSelected(false);
        mTvMessageForCompany.setSelected(false);
        mTvMessageForFriends.setSelected(false);
        mTvNoticeForGroupOwner.setSelected(false);
        mTvMessageForSystem.setSelected(false);
        mTvNoticeForService.setSelected(false);
        mTvNoticeForSystem.setSelected(false);
        mTvLovingHeart.setSelected(false);
        mTvAdvertising.setSelected(false);
        mTvShopping.setSelected(false);
        mMessageList.clear();
        mRlUnderway.setSelected(false);
        mRlOver.setSelected(false);
        mRlActivityFlat.setSelected(false);
        mIvYiShenHe.setVisibility(View.GONE);
        mIvShenHeZhong.setVisibility(View.GONE);
        mIvYiShenHe2.setVisibility(View.GONE);
    }

    private void reLoad(int states) {
        switch (states) {
            case 0://@我
//                load();
//                conversationListView = (EaseConversationList) getView().findViewById(R.id.list_ease_conversation);
//                conversationListView.init(conversationList);
//                toShow(1);
//                conversationListView.refresh();
//                conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                        Bundle bundle = new Bundle();
//                        bundle.putInt("states", 3);//1群聊 2 单位 3单聊
//                        bundle.putString("user_id", conversationList.get(i).conversationId());
//                        ActivityUtils.startActivity(mContext, ChatAllActivity.class, bundle);
//                    }
//                });

                pageNo = 1;
                doNetWOrk(3);
                toShow(0);

                break;
            case 1:
                load();
                conversationListView = (EaseConversationList) getView().findViewById(R.id.list_ease_conversation);
                conversationListView.init(conversationListForGroup);
                toShow(1);
                conversationListView.refresh();

                conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Bundle bundle = new Bundle();
                        bundle.putInt("states", 1);//1群聊 2 单位 3单聊
                        bundle.putString("user_id", conversationListForGroup.get(i).conversationId());
                        String name = conversationListForGroup.get(i).getExtField();
                        String name1 = conversationListForGroup.get(i).getExtField();
                        conversationListForGroup.get(i).setExtField(name);
                        bundle.putString("usrName", name);
                        ActivityUtils.startActivity(mContext, ChatAllActivity.class, bundle);
                    }
                });
                break;
            case 2:
                load();
                conversationListView = (EaseConversationList) getView().findViewById(R.id.list_ease_conversation);
                conversationListView.init(conversationListForCompany);
                toShow(1);
                conversationListView.refresh();
                conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Bundle bundle = new Bundle();
                        bundle.putInt("states", 2);//群聊 2 单位 3单聊
                        bundle.putString("user_id", conversationListForCompany.get(i).conversationId());
                        String name = conversationListForCompany.get(i).getExtField();
                        String name1 = conversationListForCompany.get(i).getExtField();
                        bundle.putString("usrName", name);
                        ActivityUtils.startActivity(mContext, ChatAllActivity.class, bundle);
                    }
                });

                break;
            case 3:
                load();
                conversationListView = (EaseConversationList) getView().findViewById(R.id.list_ease_conversation);
                conversationListView.init(conversationListForPerson);
                toShow(1);
                conversationListView.refresh();
                conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Bundle bundle = new Bundle();
                        bundle.putInt("states", 3);//群聊 2 单位 3单聊
                        bundle.putString("user_id", conversationListForPerson.get(i).conversationId());
                        bundle.putString("usrName", conversationListForPerson.get(i).getExtField());
                        bundle.putString("imFriendsId", conversationListForPerson.get(i).conversationId());
                        ActivityUtils.startActivity(mContext, ChatAllActivity.class, bundle);
                    }
                });
                break;
            case 4:
                pageNo = 1;
                doNetWOrk(typeNotifyCode);
                toShow(0);
                break;
            case 5:
                pageNo = 1;
                doNetWOrk(typeNotifyCode);
                toShow(0);
                break;
            case 6://商城
                pageNo = 1;
                doNetWOrk(3);
                toShow(0);
                break;
            case 7:
                pageNo = 1;
                toShow(2);
                doNetWOrk(typeNotifyCode);
                break;
            case 8:
                pageNo = 1;
                doNetWOrk(3);
                toShow(0);
                break;
            case 9:
                pageNo = 1;
                doNetWOrk(typeNotifyCode);
                toShow(0);
                break;
            case 10:
                pageNo = 1;
                doNetWOrk(typeNotifyCode);
                toShow(0);
                break;
        }

    }

    private void toShow(int count) {
        switch (count) {
            case 0://只显示下拉刷新
                mSwipeLayout.setVisibility(View.VISIBLE);
                mTvSystemNotifyLine.setVisibility(View.GONE);
                if (conversationListView != null)
                    conversationListView.setVisibility(View.GONE);
                if (mLlFragSystemNotify != null) {
                    mLlFragSystemNotify.setVisibility(View.GONE);
                }
                break;
            case 1://只显示消息
                mSwipeLayout.setVisibility(View.GONE);
                mTvSystemNotifyLine.setVisibility(View.GONE);
                if (conversationListView != null)
                    conversationListView.setVisibility(View.VISIBLE);
                if (mLlFragSystemNotify != null) {
                    mLlFragSystemNotify.setVisibility(View.GONE);
                }
                break;
            case 2://显示系统消息栏+刷洗
                mSwipeLayout.setVisibility(View.VISIBLE);
                mTvSystemNotifyLine.setVisibility(View.VISIBLE);
                if (conversationListView != null)
                    conversationListView.setVisibility(View.GONE);
                if (mLlFragSystemNotify != null) {
                    mLlFragSystemNotify.setVisibility(View.VISIBLE);
                }
                break;

            default:
                mSwipeLayout.setVisibility(View.VISIBLE);
                if (conversationListView != null)
                    conversationListView.setVisibility(View.GONE);
                break;
        }

    }

    protected List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    private void doNetWOrk(int type) {
        if (pageNo == 1) {
            friendsCheckAdapter.setEnableLoadMore(false);
            groupCheckAdapter.setEnableLoadMore(false);
            checkAdapter.setEnableLoadMore(false);
            noticeAdapter.setEnableLoadMore(false);
            sendLoveAdapter.setEnableLoadMore(false);
        }


        switch (type) {
            case 0://个人申请
                ApiManager.getApi().getJoinFriendsList(pageNo, 10).enqueue(new NetCallBack<AddFriendsAndGroupBean>() {
                    @Override
                    protected void onSuccess(Call<AddFriendsAndGroupBean> call, Response<AddFriendsAndGroupBean> response) {
                        if (response != null) {
                            friendsCheckAdapter.setEnableLoadMore(true);
                            AddFriendsAndGroupBean groupMemberBean = response.body();
                            isLastPage = groupMemberBean.isLastPage;
                            if (pageNo == 1 && systemNotify != null) {
                                systemNotify.clear();

                            }
                            systemNotify.addAll(groupMemberBean.dataList);
                            mLvActivityListMember.setAdapter(friendsCheckAdapter);
                            if (friendsCheckAdapter != null) {
                                friendsCheckAdapter.notifyDataSetChanged();
                            }
                            mLoadingLayout.showContent();

                            if (pageNo == 1 && systemNotify.size() == 0) {
                                mLoadingLayout.showEmpty();
                            } else if (pageNo == 1 && systemNotify.size() < 10) {
                                friendsCheckAdapter.loadMoreEnd();
                            } else if (pageNo > 1 && systemNotify.size() >= 10) {
                                friendsCheckAdapter.loadMoreEnd();
                            }
                            mSwipeLayout.setRefreshing(false);
                        } else {

                            mLoadingLayout.showError();
                            mSwipeLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onFailure(Call<AddFriendsAndGroupBean> call, Throwable t) {
                        super.onFailure(call, t);
                        mLoadingLayout.showError();
                        mSwipeLayout.setRefreshing(false);
                    }
                });


                break;
            case 1://群申请
                ApiManager.getApi().getJoinApplicationList(pageNo, 10).enqueue(new NetCallBack<AddFriendsAndGroupBean>() {
                    @Override
                    protected void onSuccess(Call<AddFriendsAndGroupBean> call, Response<AddFriendsAndGroupBean> response) {
                        if (response != null) {
                            groupCheckAdapter.setEnableLoadMore(true);
                            AddFriendsAndGroupBean groupMemberBean = response.body();
                            isLastPage = groupMemberBean.isLastPage;
                            if (pageNo == 1 && systemNotify != null) {
                                systemNotify.clear();

                            }
                            systemNotify.addAll(groupMemberBean.dataList);
                            mLvActivityListMember.setAdapter(groupCheckAdapter);
                            if (groupCheckAdapter != null) {
                                groupCheckAdapter.notifyDataSetChanged();
                            }
                            mLoadingLayout.showContent();

                            if (systemNotify.size() == 0) {
                                mLoadingLayout.showEmpty();
                            } else if (pageNo == 1 && systemNotify.size() < 10) {
                                groupCheckAdapter.loadMoreEnd();
                            } else if (pageNo > 1 && systemNotify.size() >= 10) {
                                groupCheckAdapter.loadMoreEnd();
                            }
                            mSwipeLayout.setRefreshing(false);
                        } else {

                            mLoadingLayout.showError();
                            mSwipeLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onFailure(Call<AddFriendsAndGroupBean> call, Throwable t) {
                        super.onFailure(call, t);
                        mLoadingLayout.showError();
                        mSwipeLayout.setRefreshing(false);
                    }
                });
                break;
            case 2://平台申请
                ApiManager.getApi().getJoinplateformList(pageNo, 10).enqueue(new NetCallBack<AddFriendsAndGroupBean>() {
                    @Override
                    protected void onSuccess(Call<AddFriendsAndGroupBean> call, Response<AddFriendsAndGroupBean> response) {
                        if (response != null) {
                            checkAdapter.setEnableLoadMore(true);
                            AddFriendsAndGroupBean groupMemberBean = response.body();
                            isLastPage = groupMemberBean.isLastPage;
                            if (systemNotify != null) {
                                systemNotify.clear();

                            }
                            systemNotify.addAll(groupMemberBean.dataList);
                            mLvActivityListMember.setAdapter(checkAdapter);
                            if (checkAdapter != null) {
                                checkAdapter.notifyDataSetChanged();
                            }
                            mLoadingLayout.showContent();
                            if (pageNo == 1 && systemNotify.size() == 0) {
                                mLoadingLayout.showEmpty();
                            } else if (pageNo == 1 && systemNotify.size() < 10) {
                                checkAdapter.loadMoreEnd();
                            } else if (pageNo > 1 && systemNotify.size() >= 10) {
                                checkAdapter.loadMoreEnd();
                            }
                            mSwipeLayout.setRefreshing(false);
                        } else {

                            mLoadingLayout.showError();
                            mSwipeLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onFailure(Call<AddFriendsAndGroupBean> call, Throwable t) {
                        super.onFailure(call, t);
                        mLoadingLayout.showError();
                        mSwipeLayout.setRefreshing(false);
                    }
                });
                break;
            case 3://群主公告(包含单位)
                ApiManager.getApi().getGroupNotice(pageNo, 10).enqueue(new NetCallBack<NoticeBean>() {
                    @Override
                    protected void onSuccess(Call<NoticeBean> call, Response<NoticeBean> response) {
                        if (response != null) {
                            noticeAdapter.setEnableLoadMore(true);
                            NoticeBean noticeBean = response.body();
                            isLastPage = noticeBean.isLastPage;
                            if (pageNo == 1 && dataList != null) {
                                dataList.clear();

                            }
                            if (noticeBean != null) {
                                dataList.addAll(noticeBean.dataList);
                                mLvActivityListMember.setAdapter(noticeAdapter);
                            }

                            mLoadingLayout.showContent();
                            if (dataList.size() == 0) {
                                mLoadingLayout.showEmpty();
                            } else if (pageNo == 1 && dataList.size() < 10) {
                                noticeAdapter.loadMoreEnd();
                            } else if (pageNo > 1 && dataList.size() >= 10) {
                                noticeAdapter.loadMoreEnd();
                            }
                            mSwipeLayout.setRefreshing(false);
                        } else {

                            mLoadingLayout.showError();
                            mSwipeLayout.setRefreshing(false);
                        }

                        if (noticeAdapter != null) {
                            noticeAdapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
            case 4://平台公告
                ApiManager.getApi().getPlateformNotice(pageNo, 10).enqueue(new NetCallBack<NoticeBean>() {
                    @Override
                    protected void onSuccess(Call<NoticeBean> call, Response<NoticeBean> response) {
                        if (response != null) {
                            noticeAdapter.setEnableLoadMore(true);
                            NoticeBean noticeBean = response.body();
                            isLastPage = noticeBean.isLastPage;
                            if (pageNo == 1 && dataList != null) {
                                dataList.clear();

                            }
                            if (noticeBean != null) {
                                dataList.addAll(noticeBean.dataList);
                                mLvActivityListMember.setAdapter(noticeAdapter);
                            }

                            mLoadingLayout.showContent();
                            if (dataList.size() == 0) {
                                mLoadingLayout.showEmpty();
                            } else if (pageNo == 1 && dataList.size() < 10) {
                                noticeAdapter.loadMoreEnd();
                            } else if (pageNo > 1 && dataList.size() >= 10) {
                                noticeAdapter.loadMoreEnd();
                            }
                            mSwipeLayout.setRefreshing(false);
                        } else {

                            mLoadingLayout.showError();
                            mSwipeLayout.setRefreshing(false);
                        }

                        if (noticeAdapter != null) {
                            noticeAdapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
            case 5://系统公告
                ApiManager.getApi().getSystemNotify(pageNo, 10).enqueue(new NetCallBack<NoticeBean>() {
                    @Override
                    protected void onSuccess(Call<NoticeBean> call, Response<NoticeBean> response) {
                        if (response != null) {
                            noticeAdapter.setEnableLoadMore(true);
                            NoticeBean noticeBean = response.body();
                            isLastPage = noticeBean.isLastPage;
                            if (pageNo == 1 && dataList != null) {
                                dataList.clear();

                            }
                            if (noticeBean != null) {
                                dataList.addAll(noticeBean.dataList);
                                mLvActivityListMember.setAdapter(noticeAdapter);
                            }

                            mLoadingLayout.showContent();

                            if (dataList.size() == 0) {
                                mLoadingLayout.showEmpty();
                            } else if (pageNo == 1 && dataList.size() < 10) {
                                noticeAdapter.loadMoreEnd();
                            } else if (pageNo > 1 && dataList.size() >= 10) {
                                noticeAdapter.loadMoreEnd();
                            }
                            mSwipeLayout.setRefreshing(false);
                        } else {

                            mLoadingLayout.showError();
                            mSwipeLayout.setRefreshing(false);
                        }

                        if (noticeAdapter != null) {
                            noticeAdapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
            case 6://爱心
                ApiManager.getApi().getLoveNotifyList(pageNo, 10).enqueue(new NetCallBack<SendLoveNotifyDetailsBean>() {
                    @Override
                    protected void onSuccess(Call<SendLoveNotifyDetailsBean> call, Response<SendLoveNotifyDetailsBean> response) {
                        if (response != null) {
                            sendLoveAdapter.setEnableLoadMore(true);
                            SendLoveNotifyDetailsBean noticeBean = response.body();
                            isLastPage = noticeBean.isLastPage;
                            if (pageNo == 1 && dataList != null) {
                                dataList.clear();

                            }
                            if (noticeBean != null) {
                                dataList.addAll(noticeBean.dataList);
                                mLvActivityListMember.setAdapter(sendLoveAdapter);
                            }

                            mLoadingLayout.showContent();
                            if (dataList.size() == 0) {
                                mLoadingLayout.showEmpty();
                            } else if (pageNo == 1 && dataList.size() < 10) {
                                sendLoveAdapter.loadMoreEnd();
                            } else if (pageNo > 1 && dataList.size() >= 10) {
                                sendLoveAdapter.loadMoreEnd();
                            }
                            mSwipeLayout.setRefreshing(false);
                        } else {

                            mLoadingLayout.showError();
                            mSwipeLayout.setRefreshing(false);
                        }

                        if (noticeAdapter != null) {
                            noticeAdapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
            case 7://广告
                ApiManager.getApi().getAdvertisingList(pageNo, 10).enqueue(new NetCallBack<SendLoveNotifyDetailsBean>() {
                    @Override
                    protected void onSuccess(Call<SendLoveNotifyDetailsBean> call, Response<SendLoveNotifyDetailsBean> response) {
                        if (response != null) {
                            sendLoveAdapter.setEnableLoadMore(true);
                            SendLoveNotifyDetailsBean noticeBean = response.body();
                            isLastPage = noticeBean.isLastPage;
                            if (pageNo == 1 && dataList != null) {
                                dataList.clear();

                            }
                            if (noticeBean != null) {

                                dataList.addAll(noticeBean.dataList);
                                mLvActivityListMember.setAdapter(sendLoveAdapter);
                            }

                            mLoadingLayout.showContent();

                            if (dataList.size() == 0) {
                                mLoadingLayout.showEmpty();
                            } else if (pageNo == 1 && dataList.size() < 10) {
                                sendLoveAdapter.loadMoreEnd();
                            } else if (pageNo > 1 && dataList.size() >= 10) {
                                sendLoveAdapter.loadMoreEnd();
                            }
                            mSwipeLayout.setRefreshing(false);
                        } else {

                            mLoadingLayout.showError();
                            mSwipeLayout.setRefreshing(false);
                        }

                        if (noticeAdapter != null) {
                            noticeAdapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
        }


    }


    @Override
    public void onLoadMoreRequested() {
        if (isLastPage) {
            switch (typeNotifyCode) {
                case 0:
                    friendsCheckAdapter.loadMoreEnd();
                case 1:
                    groupCheckAdapter.loadMoreEnd();
                    break;
                case 2:
                    checkAdapter.loadMoreEnd();
                    break;
                case 3:
                    noticeAdapter.loadMoreEnd();
                    break;
                case 4:
                    noticeAdapter.loadMoreEnd();
                    break;
                case 5:
                    noticeAdapter.loadMoreEnd();
                    break;
                case 6:
                    sendLoveAdapter.loadMoreEnd();
                    break;
                case 7:
                    sendLoveAdapter.loadMoreEnd();
                    break;
            }
        } else {
            pageNo++;
            doNetWOrk(typeNotifyCode);
        }
    }
}
